'use strict'

const Controller = require('egg').Controller

class TodoController extends Controller {
  // 列表
  async index() {
    const { ctx } = this

    // 目前根据项目和用户来查询
    const { pid, uid } = ctx.query

    const res = await ctx.model.Todo.find({ pid, owner: uid })

    ctx.body = { code: 2000, data: res, msg: 'todos' }
  }

  // 详情
  async show() {
    return {}
  }

  // 新建
  async create() {
    const { ctx } = this
    const { pid, ...rest } = ctx.request.body
    const owner = ctx.session.userId

    const res = await ctx.model.Todo.create({ pid, owner, ...rest })
    ctx.body = { code: 2000, data: res._id, msg: '新增任务成功' }
  }

  // 更新
  async update() {
    const { ctx } = this
    const { id } = ctx.params
    const updatedFields = ctx.request.body

    try {
      const todo = await ctx.model.Todo.findById(id)
      if (String(todo.owner) !== String(ctx.session.userId)) {
        ctx.body = { code: 4001, data: null, msg: '没有权限修改' }
        return
      }
    } catch (err) {
      ctx.body = { code: 5000, data: null, msg: '没有找到任务' }
    }

    const updatedAt = Date.now()
    await ctx.model.Todo.findById(id).update({ updatedAt, ...updatedFields })
    ctx.body = { code: 2000, data: null, msg: '更新成功' }
  }

  // 删除
  async destroy() {
    const { ctx } = this
    const { id } = ctx.params

    let todo = null
    try {
      todo = await ctx.model.Todo.findById(id)
    } catch (err) {
      ctx.body = { code: 4001, data: null, msg: '没有找到任务' }
      return
    }

    if (String(todo.owner) !== String(ctx.session.userId)) {
      ctx.body = { code: 4002, data: null, msg: '没有权限修改当前任务' }
      return
    }

    await ctx.model.Todo.findById(id).remove()
    ctx.body = { code: 2000, data: null, msg: '任务删除成功' }
  }
}

module.exports = TodoController
